package com.test.common.concurrency;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//高并发
public class ConcurrentExample {
	//1.线程池 通过线程池来管理线程，避免频繁创建和销毁线程，从而提高系统性能。
//    private static final int THREAD_POOL_SIZE = 10;
//    private static final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
//
//    public static void main(String[] args) {
//        for (int i = 0; i < 100; i++) {
//            int taskId = i;
//            executorService.execute(() -> {
//                System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName());
//            });
//        }
//        executorService.shutdown(); // 关闭线程池
//    }
    //2并发集合  避免在多线程环境下对集合的并发修改导致的数据不一致问题。
	 public static void main5(String[] args) {
		final Map<String, Integer> count = new ConcurrentHashMap<>();
		final CountDownLatch endLatch = new CountDownLatch(2);
		Runnable task = new Runnable() {
			@Override
			public void run() {
				// synchronized (count){
				for (int i = 0; i < 5; i++) {
					Integer value = count.get("a");
					if (null == value) {
						count.put("a", 1);
					} else {
						count.put("a", value + 1);
					}
				}
				endLatch.countDown();
			//}
			}
		};
		new Thread(task).start();
		new Thread(task).start();
 
		try {
			endLatch.await();
			System.out.println(count);
		} catch (Exception e) {
			e.printStackTrace();
		}
}
	 
	 //3. 使用锁机制 1.synchronized  2.ReentrantLock类  3 ReadWriteLock接口 4 Condition接口 5 volatile关键字
	 
//	 import java.util.concurrent.locks.ReentrantLock;
//
//	 public class ReentrantLockExample {
//	     private final ReentrantLock lock = new ReentrantLock();
//
//	     public void doSomething() {
//	         lock.lock();
//	         try {
//	             // 同步代码块
//	         } finally {
//	             lock.unlock();
//	         }
//	     }
//	 }
	 //4.并发工具类CountDownLatchExample
	 
	 //5 redis 
	 //6异步编程

	     public static void main(String[] args) throws Exception {
	         CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
	             // 模拟耗时操作
	             try {
	                 Thread.sleep(2000);
	             } catch (InterruptedException e) {
	                 Thread.currentThread().interrupt();
	                 throw new IllegalStateException(e);
	             }
	             return "Async result";
	         });
	         
	         // 主线程可以继续执行其他任务
	         
	         // 获取异步结果
	         String result = future.get();
	         System.out.println(result);
	     }
	     //7.消息队列mq
	     //8使用非阻塞io  --NIO

}